﻿using System;
using System.Collections.Generic;
using System.Text;
using IM.Model;
using System.Linq;

namespace IM.BLL
{
    /// <summary>
    /// 即时消息管理
    /// </summary>
    public class InstantMessageManager
    {
        /// <summary>
        /// 所有聊天消息
        /// </summary>
        private static IList<InstantMessage> _messages = new List<InstantMessage>();

        /// <summary>
        /// 发消息
        /// </summary>
        public static void SendMessage(InstantMessage message)
        {
            _messages.Add(message);
        }

        /// <summary>
        /// 检查指定用户是否有新消息
        /// </summary>
        public static bool CheckNewMessage(int userid)
        {
            return _messages.Count(p => p.ReceiverId == userid) > 0;
        }

        /// <summary>
        /// 查询新消息
        /// </summary>
        /// <returns></returns>
        public static IList<InstantMessage> ReceiveNewMessages(int userid)
        {
            IList<InstantMessage> messages = _messages.Where(p => p.ReceiverId == userid).ToList();
            if (messages.Count > 0)
                foreach (var msg in messages)//服务器内存中删除已读信息
                {
                    _messages.Remove(msg);
                }

            return messages;
        }

        /// <summary>
        /// 将过期信息发送到信箱
        /// </summary>
        public static void SendTimeoutMessageToMessageBox()
        {
            IList<InstantMessage> messages = _messages.Where(p => p.IsTimeout).ToList();
            if (messages.Count > 0)
            {
                foreach (var msg in messages)//服务器内存中删除已读信息
                {
                    MessageManager.Add(new Message { Content = msg.Content, FromUser = msg.SenderId, MessageType = (int)msg.MessageType, IsRead = false, SendTime = msg.SendTime, Title = "", ToUser = msg.ReceiverId });
                    _messages.Remove(msg);
                }
            }
        }

        /// <summary>
        /// 获取离线信息
        /// </summary>
        /// <returns></returns>
        public static IList<InstantMessage> GetOffLineMessages(int userid)
        {
            IList<Message> msgs = MessageManager.GetOffLineMessage(userid);//获取离线消息
            MessageManager.DeleteOffLineMessage(userid);//删除掉数据库中的离线消息
            return msgs.Select(p => new InstantMessage { Content = p.Content, MessageType = (InstantMessageType)p.MessageType, ReceiverId = p.ToUser, SenderId = p.FromUser, SendTime = p.SendTime }).ToList();
        }
    }
}
